<?php
/**
 *	Laborator - Clients Logos
 *
 *	Developed by: Arlind Nushi
 *
 *	www.laborator.co
 */

/* SimpleAds module by Laborator */
class LaboratorSimpleAds
{
	private $laborator_simpleads = 'laborator_simpleads';
	private $laborator_simpleads_groups = 'laborator_simpleads_groups';
	
	private $parent_slug = '';
	private $menu_slug = 'laborator_simpleads';
	
	private $ad_sizes = array(
		"thumb"		=> array(100, 90),
		"ads_half_two" 	=> array(95, 95),
		"ads_one_one" 	=> array(235, 235)
	);
	
	public static $simpleads_instance;
	
	
	public function __construct($ps)
	{
		global $wpdb;
		
		$this->parent_slug = $ps;
		
		// Add Prefixes
		$this->laborator_simpleads = $wpdb->prefix . $this->laborator_simpleads;
		$this->laborator_simpleads_groups = $wpdb->prefix . $this->laborator_simpleads_groups;

		add_action('admin_menu', array(&$this, 'simpleads_menu'));
		
		# Process Redirects
		$s_ads_redirect_to = isset($_GET['s_ads_redirect_to']) ? $_GET['s_ads_redirect_to'] : '';
		$hash_id = isset($_GET['hash_id']) ? $_GET['hash_id'] : '';
		
		if($s_ads_redirect_to && $hash_id)
		{
			$ad = $this->get_ad($s_ads_redirect_to);
			
			if($this->validate_link($ad))
			{
				$wpdb->update($this->laborator_simpleads, array('clicks' => $ad->clicks + 1), array('simplead_id' => $s_ads_redirect_to));
				
				wp_redirect($ad->url);
				exit;
			}
		}
		
		# Admin Backend
		if(is_admin())
		{
			if(isset($_GET['page']) && $_GET['page'] == $this->menu_slug)
			{	
				// Add New Ads Group
				if(isset($_POST['add_group']) && ($group_name = $_POST['group_name']))
				{
					$this->create_ads_group($group_name);
					define("SA_UPDATE", "Group \"{$group_name}\" has been created.");
				}
				
				// Edit Ads Group
				if(isset($_POST['edit_group']) && ($group_name = $_POST['group_name']))
				{
					$group_id = $_POST['group_id'];

					
					$this->edit_ads_group($group_id, $group_name);
					define("SA_UPDATE", "Group \"{$group_name}\" has been edited.");
				}
				
				// Delete Group
				if(isset($_GET['delete_ads_group']) && ($group_id = $_GET['delete_ads_group']) && $this->delete_ads_group($group_id))
				{
					define("SA_UPDATE", "Group has been deleted.");
				}
				
				
				// New Ad Create
				if(isset($_POST['new_ad_create']))
				{
					$group_id = $_POST['group_id'];
					$ad_title = $_POST['ad_title'];
					$url = $_POST['url'];
					
					$ad_image = $_FILES['ad_image'];
					
					if(strstr($ad_image['type'], 'image'))
					{
						$this->new_ad_create($group_id, $ad_title, $url, $ad_image);
						
						define("SA_UPDATE", "Ad has been created.");
					}
					else
					{
						define("SA_ERROR", "Invalid image format! <a href=javascript:history.go(-1);>Go back</a>");
					}
				}
				
				// Edit Ad
				if(isset($_POST['edit_ad']) && ($simplead_id = $_POST['simplead_id']))
				{
					$group_id = $_POST['group_id'];
					$ad_title = $_POST['ad_title'];
					$url = $_POST['url'];

					$ad_image = $_FILES['ad_image'];
					
					$this->edit_ad($simplead_id, $group_id, $ad_title, $url);
					
					$modified = TRUE;
					
					if($ad_image['name'])
					{
						if(strstr($ad_image['type'], 'image'))
						{
							$this->replace_ad_image($simplead_id, $ad_image);
						}
						else
						{
							$errors = TRUE;
						}
					}
					
					if($errors)
						define("SA_ERROR", "Invalid image format! <a href=javascript:history.go(-1);>Go back</a>");
					else
					if($modified)
						define("SA_UPDATE", "Ad has been edited successfully.");
					
					
					#$this->edit_ads_group($group_id, $group_name);
				}
				
				
				// Delete Ad
				if(isset($_GET['delete_ad_id']) && ($simplead_id = $_GET['delete_ad_id']) && $this->delete_ad($simplead_id))
				{
					define("SA_UPDATE", "Ad has been deleted.");
				}
			}
		}
		
		/* Register Widget */
		register_widget('SimpleAdsWidget');
		
		# Save Instance for Widget Use
		self::$simpleads_instance = $this;
	}
	
	
	public function simpleads_menu()
	{
		$parent_slug = $this->parent_slug;
		
		$page_title = 'Laborator - Simple Ads System';
		$menu_title = 'SimpleAds';
		$capability = 'administrator';
		$menu_slug = $this->menu_slug;
		$function = array( & $this, 'admin_main_page');
		
		add_submenu_page( $parent_slug, $page_title, $menu_title, $capability, $menu_slug, $function );
	}
	
	
	public function get_ad_sizes()
	{
		return $this->ad_sizes;
	}
	
	
	/* Admin Page for module */
	public function admin_main_page()
	{	
		switch(strtolower((isset($_GET['action']) ? $_GET['action'] : '')))
		{
			case 'add_group':
				$this->admin_add_group_page();
				return;
			
			case 'edit_ad_group':
				$ad_group = $this->get_ads_group($_GET['group_id']);
				
				if($ad_group)
				{
					$this->admin_add_group_page($ad_group);
					return;
				}
				
			case 'new_ad':
				$this->admin_new_ad_page();
				return;
			
			case 'edit_ad':
				$ad = $this->get_ad($_GET['id']);
				
				if($ad)
				{
					$this->admin_new_ad_page($ad);
					return;
				}
		}
		
		$groups = $this->get_ads_groups();
		$ads = $this->get_ads();
?>
<style>
.ads {
	float: left;
	margin-right: 50px;
	width: 830px;
}

.ads table {
	width: 100% !important;
	margin-bottom: 15px;
}

.ads table .pad {
	padding: 8px 10px;
}

.ad_groups {
	float: left;
	width: 300px;
	padding-right: 20px;
}

.groups {
	
}

.groups li {
	background: #EEE;
	border-radius: 3px;
	padding: 8px;
}

.groups li .links {
	display: none;
	float: right;
}

.groups li:hover .links {
	display: block;
}

.border_img {
	border: 5px solid #FFF;
	box-shadow: 0px 0px 1px rgba(0,0,0,0.5);
}

#poststuff {
	padding-top: 0px;
}
</style>
<script type="text/javascript">
jQuery(function($)
{
	$(".confirm_group_delete").on('click', function(e)
	{
		if( ! confirm('Are you sure you want to delete this group?'))
		{
			e.preventDefault();
		}
	});
	
	$(".confirm_ad_delete").on('click', function(e)
	{
		if( ! confirm('Are you sure you want to delete this ad?'))
		{
			e.preventDefault();
		}
	});
});
</script>
<div class="wrap">
	<h2>
		SimpleAds by Laborator
		<a href="admin.php?page=<?php echo $_GET['page']; ?>&action=add_group" class="add-new-h2">Add New Group</a>
		<a href="admin.php?page=<?php echo $_GET['page']; ?>&action=new_ad" class="add-new-h2">New Ad</a>
	</h2>
	
<?php if(defined("SA_ERROR")): ?>
<div id="message" class="error below-h2">
	<p><?php echo SA_ERROR; ?></p>
</div>
<?php elseif(defined("SA_UPDATE")): ?>
<div id="message" class="updated below-h2">
	<p><?php echo SA_UPDATE; ?></p>
</div>
<?php endif; ?>

	<br />
	
	<div class="ads">
		
		<table class="wp-list-table widefat  posts" cellspacing="0">
			
			<thead>
				<tr>
					<th width="100">Image</th>
					<th width="200">Title</th>
					<th width="250">Group</th>
					<th width="75">Link</th>
					<th width="75">Clicks</th>
					<th width="100">Action</th>
				</tr>
			</thead>
			
			<tbody>
			<?php 
			if(count($ads) > 0):
			
				foreach($ads as $ad):
				
					$id = $ad->simplead_id;
					
					$images = $ad->images;
					$thumb = $images->thumb;
					
					$title = $ad->title;
					$url = $ad->url;
					$clicks = $ad->clicks;
					
					$group_id = $ad->group_id;
					$group_name = $this->get_ads_group($group_id)->group_name;
					
					$group_name = $group_name ? $group_name : 'N/A';
					
				?>
				<tr>
					<td>
						<a href="<?php echo $images->original; ?>" target="_blank">
							<img class="border_img" src="<?php echo $thumb; ?>" width="<?php echo $this->ad_sizes['thumb'][0]; ?>" />
						</a>
					</td>
					<td><?php echo $title; ?></td>
					<td><?php echo $group_name; ?></td>
					<td>
						<?php if($url): ?>
							<a href="<?php echo $url; ?>" target="_blank">Open</a>
						<?php else: ?>
						N/A
						<?php endif; ?>
					</td>
					<td><?php echo $clicks; ?></td>
					<td>
						<a href="<?php echo "admin.php?page={$_GET['page']}&action=edit_ad&id={$id}"; ?>">Edit</a> |
						<a href="<?php echo "admin.php?page={$_GET['page']}&delete_ad_id={$id}"; ?>" class="confirm_ad_delete">Delete</a>
					</td>
				</tr>
				<?php
				
				endforeach;
			
			else: 
			?>
				<tr>
					<td colspan="5" class="pad">No records</td>
				</tr>
			<?php 
			endif; 
			?>
			</tbody>
			
		</table>
		
	</div>
	
	<div id="poststuff" class="ad_groups">		
		<div class="postbox-container">
			<div class="postbox">
				<h3>Groups</h3>
			
				<div class="inside">
				<ul class="groups">
				<?php
				foreach($groups as $group):
				?>
				<li>
					<?php echo $group->group_name; ?>
					<div class="links">
						<a href="<?php echo "admin.php?page={$_GET['page']}&action=edit_ad_group&group_id={$group->group_id}"; ?>">Edit</a>
						<a href="<?php echo "admin.php?page={$_GET['page']}&delete_ads_group={$group->group_id}"; ?>" class="confirm_group_delete">Delete</a>
					</div>
				</li>
				<?php
				endforeach;
				
				if(count($groups) == 0):
				?>
				<span>No groups.</span>
				<?php
				endif;
				?>
				</ul>
				</div>
			</div>
		</div>
	</div>
	
	<div class="clear"></div>
	
</div>
<?php
		$this->copyrights();
	}
	
	
	public function admin_add_group_page($entry = '')
	{
		if($entry)
		{
			$group_id = $entry->group_id;
			$group_name = $entry->group_name;
		}
?>
<div class="wrap">

	<h2>SimpleAds &raquo; <?php echo $entry ? 'Edit' : 'Add New'; ?> Ads Group</h2>

	<form method="post" action="admin.php?page=<?php echo $_GET['page']; ?>" enctype="multipart/form-data">
	<?php if($entry): ?>
	<input type="hidden" name="group_id" value="<?php echo $group_id; ?>" />
	<?php endif; ?>
	
	<table class="form-table">
		<tbody>
			<tr>
				<th>
					<label for="group_name">Group Name:</label>
				</th>
				<td>
				
					<input type="text" id="group_name" name="group_name" class="regular-text" required="required" placeholder="Sample Group" value="<?php echo isset($group_name) ? esc_attr($group_name) : ''; ?>" />
				</td>
			</tr>
		</tbody>
	</table>
	
	<p>
		<?php if($entry): ?>
		<button type="submit" name="edit_group" class="button-primary">Edit Group</button>
		<?php else: ?>
		<button type="submit" name="add_group" class="button-primary">Add Group</button>
		<?php endif; ?>
	</p>

<br />
<a href="admin.php?page=<?php echo $_GET['page']; ?>">&laquo; Go Back</a>

</div>
<?php
	}
	
	public function admin_new_ad_page($entry = '')
	{
		if($entry)
		{
			$simplead_id = $entry->simplead_id;
			$group_id = $entry->group_id;
			$ad_image = $entry->ad_image;
			$ad_title = $entry->title;
			$url = $entry->url;
			$clicks = $entry->clicks;
		}
		
		$groups = $this->get_ads_groups();
?>
<div class="wrap">

	<h2>SimpleAds &raquo; <?php echo $entry ? 'Edit Ad' : 'New Ad'; ?></h2>

	<form method="post" action="admin.php?page=<?php echo $_GET['page']; ?>" enctype="multipart/form-data">
	<?php if($entry): ?>
	<input type="hidden" name="simplead_id" value="<?php echo $simplead_id; ?>" />
	<?php endif; ?>
	
	<style>
	
	.current_image {
		margin-top: 10px;
	}
		
	.border_img {
		border: 5px solid #FFF;
		box-shadow: 0px 0px 1px rgba(0,0,0,0.5);
	}

	</style>
	
	
	<table class="form-table">
		<tbody>
			<tr>
				<th>
					<label for="group_id">Group ID:</label>
				</th>
				<td>
				
					<select id="group_id" name="group_id">
					<?php
					foreach($groups as $group):
					?>
					<option<?php echo $group_id == $group->group_id ? ' selected="selected"' : ''; ?> value="<?php echo $group->group_id; ?>"><?php echo $group->group_name; ?></option>
					<?php
					endforeach;
					
					if( ! count($groups)):
					?>
					<option value="0">N/A</option>
					<?php
					endif;
					?>
					</select>
				</td>
			</tr>
			<tr>
				<th>
					<label for="ad_title">Ad Title:</label>
				</th>
				<td>
				
					<input type="text" id="ad_title" name="ad_title" class="regular-text" required="required" value="<?php echo esc_attr($ad_title); ?>" />
				</td>
			</tr>
			<tr>
				<th>
					<label for="url">Source URL:</label>
				</th>
				<td>
				
					<input type="text" id="url" name="url" class="regular-text" required="required" placeholder="http://" value="<?php echo esc_attr($url); ?>" />
				</td>
			</tr>
			<tr>
				<th>
					<label for="ad_image">Ad Image:</label>
				</th>
				<td>
				
					<input type="file" id="ad_image" name="ad_image" value="<?php echo esc_attr($ad_image); ?>" />
					
					<?php if($entry && $entry->images->thumb): ?>
					<div class="current_image">
						<a href="<?php echo $entry->images->original; ?>" target="_blank">
							<img class="border_img" src="<?php echo $entry->images->thumb; ?>" width="<?php echo $this->ad_sizes['thumb'][0]; ?>" />
						</a>
					</div>
					<p class="desc">If you want to replace this image, upload new one.</p>
					<?php endif; ?>
					
					<p class="desc">Supported sizes: <?php 
						
						$s = $this->get_ad_sizes();
						unset($s['thumb']);
						
						$i = 0;
						foreach($s as $index => $size)
						{
							if($i > 0)
								echo ", ";
								
							echo "{$size[0]}x{$size[1]}";
							$i++;
						}
					?></p>
				</td>
			</tr>
		</tbody>
	</table>
	
	<p>
		<?php if($entry): ?>
		<button type="submit" name="edit_ad" class="button-primary">Edit Ad</button>
		<?php else: ?>
		<button type="submit" name="new_ad_create" class="button-primary">New Ad</button>
		<?php endif; ?>
	</p>

<br />
<a href="admin.php?page=<?php echo $_GET['page']; ?>">&laquo; Go Back</a>

</div>
<?php
	}
	
	public function copyrights()
	{
		?>
		<style>
			.copyrights { color: #777; }
		</style>
		<div class="copyrights">
			&copy; <strong>SimpleAds</strong> created by <a href="http://laborator.co" target="_blank">Laborator</a> team.
		</div>
		<?php
	}
	
	
	/* DB Api */
	public function create_ads_group($group_name)
	{
		global $wpdb;
		
		if($group_name)
		{
			$wpdb->insert($this->laborator_simpleads_groups, array('group_name' => $group_name));
			
			return TRUE;
		}
		
		return FALSE;
	}
	
	public function get_ads_group($group_id)
	{
		global $wpdb;
		
		$row = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $this->laborator_simpleads_groups WHERE group_id = %d", $group_id) );
		
		
		return $row;
	}
	
	public function get_ads_groups()
	{
		global $wpdb;
		
		return $wpdb->get_results( 
			$wpdb->prepare("SELECT * FROM $this->laborator_simpleads_groups ORDER BY group_id ASC") 
		);
	}
	
	public function delete_ads_group($group_id)
	{
		global $wpdb;
		
		$query = $wpdb->query( 
			$wpdb->prepare("DELETE FROM $this->laborator_simpleads_groups WHERE group_id = %d", $group_id) 
		);
		
		return $query;
	}
	
	public function edit_ads_group($group_id, $group_name)
	{
		global $wpdb;
		
		$query = $wpdb->query( 
			$wpdb->prepare("UPDATE $this->laborator_simpleads_groups SET group_name = %s WHERE group_id = %d", $group_name, $group_id) 
		);
	}
	
	public function new_ad_create($group_id, $ad_title, $url, $ad_image)
	{
		global $wpdb;
		
		# Images Creation
		$ad_image_arr = $this->upload_image($ad_image);
		$ad_image_s = serialize($ad_image_arr);
		
		# Datas to insert
		$datas = array(
			'group_id' => $group_id,
			'title' => $ad_title,
			'url' => $url,
			'ad_image' => $ad_image_s
		);
		
		
		$wpdb->insert($this->laborator_simpleads, $datas);
		
		
		return TRUE;
	}
	
	public function upload_image($files_instance)
	{
		if( ! function_exists('wp_handle_upload'))
		{
			include_once(ABSPATH . 'wp-admin/includes/file.php');
		}
		
		# Do Some Tricks...
		$_POST['action'] = 'simplead_handle_upload';
		
		$override['test_form'] = false;
        $override['action'] = 'simplead_handle_upload';
        
		$image_path = wp_handle_upload($files_instance, $override);
		
		$original_image = $image_path['file'];
		
		$images = array();
		
		if($original_image)
		{
			// Generate Sizes
			foreach($this->ad_sizes as $prefix => $size)
			{
				$w = $size[0];
				$h = $size[1];
				
				$new_file = dirname($file) . "/{$prefix}_" . basename($file);
				
				#$thumb = image_resize($original_image, $w, $h, true);
				
				$thumb = dirname($original_image) . "/{$prefix}_" . basename($original_image);
				
				# Zebra Image Ressize
				$img = new Zebra_Image();
				$img->enlarge_smaller_images = FALSE;
				$img->source_path = $original_image;
				$img->target_path = $thumb;
				
				$img->resize($w, $h, ZEBRA_IMAGE_CROP_CENTER, '#FFF');
				
				$images[$prefix] = _wp_relative_upload_path($thumb);
			}
			
			$images['original'] = _wp_relative_upload_path($original_image);
		}
		
		return $images;
	}
	
	public function get_ad($simplead_id)
	{
		global $wpdb;
		
		$row = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $this->laborator_simpleads WHERE simplead_id = %d", $simplead_id) );
		
		if($row)
		{
			$upload_dir = wp_upload_dir();
			
			$row->ad_image = unserialize($row->ad_image);
			$row->images = (object)array();
			
			foreach($row->ad_image as $index => $img_url)
			{
				if(gettype($img_url) == 'string')
					$row->images->$index = $upload_dir['baseurl'] . '/' . $img_url;
			}
		}
		
		return $row;
	}
	
	public function get_ads()
	{
		global $wpdb;
		
		$results = $wpdb->get_results( $wpdb->prepare("SELECT * FROM {$this->laborator_simpleads} ORDER BY group_id ASC, simplead_id ASC") );
		$upload_dir = wp_upload_dir();
		
		foreach($results as $result)
		{
			$result->ad_image = unserialize($result->ad_image);
			$result->images = (object)array();
			
			foreach($result->ad_image as $index => $img_url)
			{
				if(gettype($img_url) == 'string')
					$result->images->$index = $upload_dir['baseurl'] . '/' . $img_url;
				
			}
		}
		
		
		return $results;
	}
	
	public function edit_ad($simplead_id, $group_id, $ad_title, $url)
	{
		global $wpdb;
		
		$wpdb->update($this->laborator_simpleads, array('group_id' => $group_id, 'title' => $ad_title, 'url' => $url), array('simplead_id' => $simplead_id));
	}
	
	public function replace_ad_image($simplead_id, $files_instance)
	{
		global $wpdb;
		
		if($ad = $this->get_ad($simplead_id))
		{
			$upload_dir = wp_upload_dir();
			
			foreach($ad->ad_image as $index => $img_url)
			{
				@unlink($upload_dir['basedir'] . '/' . $img_url);
			}
			
			$new_image = $this->upload_image($files_instance);
			
			# Images Creation
			$ad_image_s = serialize($new_image);
			
			
			$wpdb->update($this->laborator_simpleads, array('ad_image' => $ad_image_s), array('simplead_id' => $simplead_id));
		}
		
		return FALSE;
	}
	
	public function delete_ad($simplead_id)
	{
		global $wpdb;
		
		if($ad = $this->get_ad($simplead_id))
		{
			$upload_dir = wp_upload_dir();
			
			foreach($ad->ad_image as $index => $img_url)
			{
				if(gettype($img_url) == 'string')
					@unlink($upload_dir['basedir'] . '/' . $img_url);
			}
			
			$wpdb->query( $wpdb->prepare("DELETE FROM {$this->laborator_simpleads} WHERE simplead_id = %d", $simplead_id) );
			
			return TRUE;
		}
		
		return FALSE;
	}
	
	public function group_exists($group_id)
	{
		global $wpdb;
		
		$rows = $wpdb->get_var( $wpdb->prepare("SELECT COUNT(*) FROM $this->laborator_simpleads_groups WHERE group_id = %d", $group_id));
		
		return $rows > 0;
	}
	
	
	public function get_ads_to_show($options = array())
	{
		global $wpdb;
		
		$ad_size 	= $options['ad_size'];
		$group_id 	= $options['group_id'];
		$ads_count	= $options['limit'];
		
		$ads = array();
		$dimensions = $this->ad_sizes[$ad_size];
		
		if(count($dimensions))
		{
			if($group_id && $this->group_exists($group_id))
			{
				$ads = $wpdb->get_results($wpdb->prepare("SELECT * FROM $this->laborator_simpleads WHERE group_id = %d ORDER BY RAND() LIMIT 0, %d", $group_id, $ads_count));
			}
			else
			{
				$ads = $wpdb->get_results($wpdb->prepare("SELECT * FROM $this->laborator_simpleads ORDER BY RAND() LIMIT 0, %d", $ads_count));
			}
			
			$upload_dir = wp_upload_dir();
			
			foreach($ads as $result)
			{
				$result->ad_image = unserialize($result->ad_image);
				$result->images = (object)array();
				
				foreach($result->ad_image as $index => $img_url)
				{
					if(gettype($img_url) == 'string')
						$result->images->$index = $upload_dir['baseurl'] . '/' . $img_url;
				}
			}

		}
		
		return $ads;
	}
	
	
	public function generate_link($ad)
	{
		$hash_id = md5($ad->simplead_id . $ad->title);
		return site_url("/?s_ads_redirect_to={$ad->simplead_id}&hash_id={$hash_id}&ref=simpleads");
	}
	
	public function validate_link($ad)
	{
		$_hash_id = $_GET['hash_id'];
		
		$hash_id = md5($ad->simplead_id . $ad->title);
		
		return ($hash_id == $_hash_id);
	}
}


/* SimpleAds Widget */
class SimpleAdsWidget extends WP_Widget
{	
	public function __construct()
	{
		parent::__construct(false, '[Laborator] SimpleAds', array('description' => 'Advertising widget for SimpleAds module. This widget is developed by Laborator team.'));
	}
	
	
	public function widget($args, $instance)
	{
		global $wpdb, $post_id, $pagenow;

		# to show widget or not?
		if(defined("CURRENT_POST_ID"))
			$post_id = CURRENT_POST_ID;
		
		$page_template = get_post_meta($post_id, '_wp_page_template', TRUE);
		$show_on = $instance['show_on'];
		
		if($show_on && $show_on != 'all')
		{			
			# Do not show ads if page specific id is not met
			if(is_numeric($show_on) && $show_on != $post_id)
			{
				return;
			}
			else
			if(is_string($show_on))
			{
				if($show_on == 'single-post.php' && ! is_single())
					return;
				else
				if($show_on != $pagenow && $show_on != $page_template)
					return;
			}
		}
		
		
		
				
		extract($args);
		
		# Make Query for advertisement selection
		$simpleads = LaboratorSimpleAds::$simpleads_instance;
		
		$ad_size = $instance['ad_size'];
		$group_id = $instance['group_id'];
		$ads_count = $instance['ads_count'];
		
		$ads = $simpleads->get_ads_to_show(array('ad_size' => $ad_size, 'group_id' => $group_id, 'limit' => $ads_count));
		
		
		// Before Widget
		echo PHP_EOL . $before_widget;
		
		// Display Title
		$title = apply_filters('widget_title', (isset($instance['title']) ? $instance['title'] : ''), $instance, $this->id_base);
		
		if($title)
			echo PHP_EOL . $before_title . $title . $after_title . PHP_EOL;
		
		if(count($ads)):
		?>
			<div class="<?php echo $ad_size; ?>">
			<?php
			foreach($ads as $ad)
			{
				$id = $ad->simplead_id;
				$image_src = $ad->images->$ad_size;
				$link = $ad->url;
				$title = $ad->title;
				
				$link = $simpleads->generate_link($ad);
				
			?>
			<a href="<?php echo $link; ?>" target="_blank" title="<?php echo esc_attr($title); ?>">
				<img src="<?php echo $image_src; ?>" alt="ad_<?php echo $id; ?>" />
			</a>
			<?php
			}
			?>
			</div>
		<?php
		endif;
		
		
		// After Widget
		echo $after_widget . PHP_EOL;
	}
	
	
	public function update($new_instance, $old_instance)
	{
		$p = $_POST;
		
		$old_instance['ad_size'] = $p['ad_size'];
		$old_instance['group_id'] = $p['group_id'];
		$old_instance['ads_count'] = $p['ads_count'];
		$old_instance['show_on'] = $p['show_on'];
		
		return $old_instance;
	}
	
	
	public function form($instance)
	{
		$simpleads = LaboratorSimpleAds::$simpleads_instance;
		
		$groups = $simpleads->get_ads_groups();
		$ad_sizes = $simpleads->get_ad_sizes();
		
		# remove thumb size
		unset($ad_sizes['thumb']);
		
		# show on
		$general_pagetemplates = array(
			'all' => 'All Pages',
			'index.php' => 'Index Page',
			'blog.php' => 'Blog (1 columns)',
			'blog-2.php' => 'Blog (2 column)',
			'single-post.php' => 'Single Post (When reading post)'
		);
		
		$pages = get_posts(array('post_type' => 'page', 'numberposts' => -1, 'post_status' => 'publish'));
		
		?>
		<p>
			Select Size:<br />
			
			<select name="ad_size" style="width: 220px; margin-top: 5px;">
			<?php
			foreach($ad_sizes as $id => $size):
			?>
				<option<?php echo $instance['ad_size'] == $id ? ' selected="selected"' : ''; ?> value="<?php echo $id; ?>"><?php echo $size[0] . 'x' . $size[1]; ?></option>
			<?php
			endforeach;
			?>
			</select>
		</p>
		
		<p>
			Show Ads from Group:<br />
			
			<select name="group_id" style="width: 220px; margin-top: 5px;">
			<option value="0">Select from all groups</option>
			<?php
			foreach($groups as $group):
			?>
			<option<?php echo $instance['group_id'] == $group->group_id ? ' selected="selected"' : ''; ?> value="<?php echo $group->group_id; ?>"><?php echo $group->group_name; ?></option>
			<?php
			endforeach;
			?>
			</select>
		</p>
		
		<p>
			Ads to Show (at a time): <br />
			
			<select name="ads_count" style="width: 220px; margin-top: 5px;">
			<?php
			for($i=1; $i<=8; $i++):
			?>
			<option<?php echo $instance['ads_count'] == $i ? ' selected="selected"' : ''; ?> value="<?php echo $i; ?>"><?php echo $i; ?></option>
			<?php
			endfor;
			?>
			</select>
		</p>
		
		<p>
			Show on: <br />
			<select name="show_on" style="width: 220px; margin-top: 5px;">
				<optgroup label="General Page Templates">
				<?php
				foreach($general_pagetemplates as $page_template => $template_name)
				{
					?>
					<option value="<?php echo $page_template; ?>"<?php echo $instance['show_on'] == $page_template ? ' selected="selected"' : ''; ?>><?php echo $template_name; ?></option>
					<?php
				}
				?>
				</optgroup>
				<optgroup label="Specific Pages">
				<?php
				foreach($pages as $post)
				{
					$page_template = get_post_meta($post->ID, '_wp_page_template', TRUE);
					
					if(in_array($page_template, array('index.php', 'blog.php', 'blog-2.php'))):
					?>
					<option value="<?php echo $post->ID; ?>"<?php echo $instance['show_on'] == $post->ID ? ' selected="selected"' : ''; ?>><?php echo $post->post_title; ?></option>
					<?php
					endif;
				}
				?>
				</optgroup>
			</select>
		</p>
		<?php
	}
}



/*
 
-- SQL CODE FOR CREATING TABLES

CREATE TABLE `wp_laborator_simpleads` (
  `simplead_id` int(11) NOT NULL AUTO_INCREMENT,
  `group_id` int(11) NOT NULL,
  `url` longtext NOT NULL,
  `clicks` int(11) NOT NULL DEFAULT '0',
  `ad_image` longtext NOT NULL,
  `title` varchar(255) NOT NULL,
  PRIMARY KEY (`simplead_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;


CREATE TABLE `wp_laborator_simpleads_groups` (
  `group_id` int(11) NOT NULL AUTO_INCREMENT,
  `group_name` varchar(255) NOT NULL,
  PRIMARY KEY (`group_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

*/